/*
 * Golazo MA4
 * Copyright (C) 2008 Golazo MASHUP AWARD 4th team.
 * http://code.google.com/p/golazo/
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License 
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * serverload
 */
function serverload() {

  // dispatch 
  Golazo.dispatch(function(request, response, session) {

    // 私は誰か
    var me = Golazo.User.find(session.get('me'));
	if (!me)
	  return $('#signin')
	    .layout(/*me*/)
	    .metaRefresh('/signin.html?' + $.param({ url: request.uri }), 3);

    // GET
	if (request.method != 'POST') {

      var signature = $('#form_signature')
        .val(me.sign());

      // もうカーウィングスは無効
	  if (!me.carwings)
	    return $('#succeeded')
		  .layout(me)
	      .metaRefresh('/navion.html', 3);

      var action;

      // メモIDは期待どおりか
      var actionId = request.data.actionId;
      if (actionId) {
		if (!Golazo.Action.checkActionId(actionId))
		  throw new Error('(actionId)');
		
        // メモを検索する
		action = Golazo.Action.find(actionId);
	  }

      // カーウィングスの表示位置
	  var where = Golazo.WHERE_TOKYO;

	  if (!action) {
		action = new Golazo.Action(me);
        action.latitude = where.latitude; 
        action.longitude = where.longitude;
        action.altitude = where.altitude;
	  }

      var url = $('#navi_url')
	    .val(Jaxer.Dir.resolveUrl('/navi/?' + $.param({ token: me.carwingsToken })));

      var lat = $('#navi_lat')
	    .val(action.latitude);

      var lon = $('#navi_lon')
	    .val(action.longitude);

      var alt = $('#navi_alt')
	    .val(action.altitude);

	  var layout = $('#form')
	    .layout(me)
	    .maps();
		
	  $('pre.navi.url', layout)
		.text(url.val());

      return layout;

    // POST
	} else {
	  
	  // 署名は期待どおりか
      var signature = $('#form_signature')
        .val(request.data.signature || '');

	  if (signature.val() !== me.sign())
	    throw new Error('(signature)');

      // カーウィングスを無効にする
	  if (me.carwings) {
	    try {
	      me.carwings = 0;
		  me.save();
	    } catch (e) {
          throw new Error(''+e);
        }
	  }

	  return $('#succeeded')
	    .layout(me);
	    //.metaRefresh('/navion.html', 3);
	}
  });
};

/**
 * load
 */
function load(layout) {

  $(document.form).submit(function() {
	return true;
  });

  $(document.navi).submit(function() {
	var url = this.action + '?' + $(this).serialize();
	var width = 810;
	var height = 360;
    var top = (screen.height - height) / 2;
    var left = (screen.width - width) / 2;
	window.open(url, 'navi',
	  'top=' + top + ',' +
	  'left=' + left +  ',' + 
	  'width=' + width + ',' +
	  'height=' + height + ',' + 
	  'menubar=no,toolbar=no,status=no'
	).focus();
	return false;
  });

  // #form
  if (layout.is('#form')) {

    var lat = $('#navi_lat');
    var lon = $('#navi_lon');
    var alt = $('#navi_alt');

    var point = new GLatLng(lat.val(), lon.val());
	var zoom = parseInt(alt.val(), 10);

    var map = new GMap2(document.getElementById('map'));
    map.addControl(new GSmallMapControl());
    map.setCenter(point, zoom);

    var icon = new GIcon(G_DEFAULT_ICON);
    icon.image = 'http://maps.google.com/intl/ja_jp/mapfiles/arrow.png';
    icon.shadow = 'http://maps.google.com/intl/ja_jp/mapfiles/arrowshadow.png';
    icon.iconSize = new GSize(39, 34);
    icon.shadowSize = new GSize(39, 34);
    icon.iconAnchor = new GPoint(20, 34);
    icon.dragCrossAnchor = new GPoint(16, 8);

    var marker = new GMarker(point, { icon: icon });
    map.addOverlay(marker);

    GEvent.addListener(map, 'move', function() {
      marker.setLatLng(map.getCenter());
    });

    GEvent.addListener(map, 'moveend', function() {
      lat.val(map.getCenter().lat());
      lon.val(map.getCenter().lng());
    });

    GEvent.addListener(map, 'zoomend', function(from, to) {
      alt.val(to);
    });
  }
};
load.runat = 'client';
